﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace CabConfigProvisioning
{
    public class WspConfigProvisioner : CabCopier
    {
		protected string _sConfigPath;
		protected Dictionary<string,XmlElement> _config = new Dictionary<string,XmlElement>();
	
        public WspConfigProvisioner(FileInfo sourceCabFile, FileInfo targetCabFile, FileInfo configFile) : base(sourceCabFile, targetCabFile)
        {
        	PathPattern = "^.*$";
        	_bProcessMatching = false;
        	XmlDocument config = new XmlDocument();
			config.Load(configFile.FullName);
			_sConfigPath = configFile.FullName;
			foreach(XmlElement elem in config.SelectNodes("/configuration/file"))
			{
				string sPath = elem.Attributes["path"].Value;
				if(string.IsNullOrEmpty(sPath))
					throw new ArgumentException("Missing path in file '" + _sConfigPath + "'!");
				_resources[sPath] = new DecompressedFile(sPath);
				_config[sPath] = elem;
			}
        }
        
        public WspConfigProvisioner(string sSourceCabFilePath, string sTargetCabFilePath, string sConfigFilePath) : this(new FileInfo(sSourceCabFilePath), new FileInfo(sTargetCabFilePath), new FileInfo(sConfigFilePath))
        {
        }

        protected override bool ProcessFile(DecompressedFile file)
        {
        	XmlDocument doc = new XmlDocument();
        	doc.Load(new MemoryStream(file.Content));
			XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());
			mgr.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/");
			XmlElement node = (XmlElement) _config[file.Name].SelectSingleNode("property");
			foreach(XmlElement configElem in _config[file.Name].SelectNodes("property"))
			{
				string sKey = configElem.Attributes["key"].Value;
				if(string.IsNullOrEmpty(sKey))
					throw new ArgumentException("Missing key in file '" + _sConfigPath + "'!");
				string sValue = configElem.Attributes["value"].Value;
				XmlElement propElem = (XmlElement) doc.SelectSingleNode("/sp:Feature/sp:Properties/sp:Property[@Key='" + sKey + "']", mgr);
				propElem.Attributes["Value"].Value = sValue;
			}
			
			StringWriter stringWriter = new StringWriter();
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			XmlWriter xmlWriter = XmlTextWriter.Create(stringWriter, settings);
			doc.WriteTo(xmlWriter);
			xmlWriter.Flush();
			file.Content = Encoding.UTF8.GetBytes(stringWriter.ToString());
			_resources.Remove(file.Name);
            return true;
        }

        public override void Execute()
        {
            base.Execute();
            Dispose();
        }
		
    }
}
